<?php
/**
 * @orm tablename wb_documents
 */
class WbSiteDocument extends DomArObject {
	
	/**
	 * @orm has parent WbSite inverse documents
	 */
	public $parent;
	/**
	 * @orm char(100) not empty
	 */
	public $name;
	/**
	 * @orm char(50) not empty unique
	 * @orm validator method keyValidator
	 */
	public $key;
	/**
	 * @orm plugin DomArFile({autoRename=1r,allowedExtensions={pdf,odt,doc,xls,txt,png,jpg,gif,swf}})
	 */
	public $file;
	
	public function getValidationErrorMessages() {
		return array(
			'name' => array(
				3 => 'Dokumendi nime väli peab olema täidetud!',
			),
			'documentKey' => array(
				2 => 'Selline dokumendi võti on juba kasutusel!',
				3 => 'Dokumendi võtme väli peab olema täidetud!',
				1001 => 'Dokumendi võti tohib sisaldada ainult suuri ja väikseid ladina tähti ning numbreid ja alakriipsu!<br />Dokumendi võti ei tohi sisaldada täpitähti.',
			),
		);
	}
	
	public function keyValidator( &$value ) {
		$newValue = preg_replace( '/[a-zA-Z0-9_]/', '', $value );
		if( $newValue !== '' ) {
			return 1001;
		}
		return 0;
	}
	
	/**
	 * Return the HTML code for the download link.
	 *
	 * @param String $keyString String matched by the regular expression.
	 * @return String
	 */
	public static function getDocumentHtml( $keyString ) {
		$documentKey = preg_replace( '/#/', '', $keyString );
		if( !$document = self::query()->where('t.key = "'.$documentKey.'"')->limit(1)->commit() ) {
			return '';
		}
		return '<a href="'.$document->file->getUrl().'" target="_blank">'.$document->name.'</a>';
	}
	/**
	 * Replaces document keys in text.
	 * @param String $string
	 * @return String
	 */
	public static function replaceDocumentKeys( $string ) {
		$string = preg_replace_callback( '/(#[a-zA-Z0-9]+)/',
			create_function(
	            '$matches',
	            'return WbSiteDocument::getDocumentHtml("$matches[0]");'
	        ),$string);
		return $string;	
	}
	
}
?>